package cn.lwj.service.impl;

import cn.lwj.common.BaseContext;
import cn.lwj.common.ServiceException;
import cn.lwj.mapper.OrdersMapper;
import cn.lwj.pojo.*;
import cn.lwj.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 提交订单
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders orders) {
        log.info("新建订单数据：{}",orders.toString());

//        1.获取需要的数据

        long userId = BaseContext.getCurrentId(); // 用户id

//        获取用户信息
        User user = userService.getById(userId);

//        获取地址信息

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
//            地址信息有误
            throw new ServiceException("地址信息有误，请重新添加地址");
        }

//        获取当前用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

//        设置订单数据
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now()); // 订单时间
        LocalDateTime checkoutTime = LocalDateTime.now().plusMinutes(60); // 结账时间
        orders.setCheckoutTime(checkoutTime);
//        设置订单金额
//        根据用户查询对应订单 计算订单金额
        BigDecimal initAmount = new BigDecimal(0);
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal number = BigDecimal.valueOf(shoppingCart.getNumber());
//            数据*金额=单个菜品或套餐的总金额
            BigDecimal totalAmount = amount.multiply(number);
            initAmount = initAmount.add(totalAmount);
        }
        orders.setAmount(initAmount);
//        设置订单号
        String number = IdWorker.getIdStr();
        orders.setNumber(number);
        orders.setStatus(2);
        String userName = user.getName();
        if (user.getName() != null) {
            orders.setUserName(userName);
        }
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
//        3.新增订单
        this.save(orders);

//        4.新增订单详情
        if (orders.getId() != null) {
            // 新增订单对应的订单详情 获取购物车信息 一个订单可能对应多个订单详情
            for (ShoppingCart shoppingCart : shoppingCarts) {
                OrderDetail orderDetail = new OrderDetail();

                orderDetail.setName(shoppingCart.getName());
                orderDetail.setOrderId(orders.getId());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setAmount(shoppingCart.getAmount());
                orderDetail.setImage(shoppingCart.getImage());

                if(shoppingCart.getSetmealId() != null){
//                  说明该订单详情为套餐
                    orderDetail.setSetmealId(shoppingCart.getSetmealId());
                }

                if(shoppingCart.getDishId() != null){
//                  说明该订单详情为菜品 同时要添加口味数据
                    orderDetail.setDishId(shoppingCart.getDishId());
                    orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
                }

                orderDetailService.save(orderDetail);
            }

        }

//        5.创建订单成功后 需要清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }

    /**
     * 删除订单 根据id
     * @param id
     */
    @Transactional
    @Override
    public void deleteOrder(Long id) {
//        删除订单
        if(id != null){
            boolean res = this.removeById(id);
        }
//        删除订单对应的订单详情
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null,OrderDetail::getOrderId,id);
        orderDetailService.remove(lqw);
    }

    @Transactional
    @Override
    public void updateStatus(Orders orders) {
        System.out.println(orders.toString());
        this.updateById(orders);
        if(orders.getStatus() == 4){
//            删除订单
            this.removeById(orders.getId());
//            删除订单对应的详情信息
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId,orders.getId());
            orderDetailService.remove(lqw);
        }
    }


}
